/*
 * 版权所有 (C) 2001-2014 深圳市艾派应用系统有限公司。保留所有权利。
 * 版本：
 * 修改记录：
 *		1、2014-11-25，tfl创建。 
 */
package com.chinamobile.ln.ictenterprises.ui.fragment;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.chinamobile.ln.ictenterprises.R;
import com.chinamobile.ln.ictenterprises.common.Config;
import com.chinamobile.ln.ictenterprises.common.Constants;
import com.chinamobile.ln.ictenterprises.common.Controller;
import com.chinamobile.ln.ictenterprises.common.GlobalSetting;
import com.chinamobile.ln.ictenterprises.http.HttpAsyncTask;
import com.chinamobile.ln.ictenterprises.model.Node;
import com.chinamobile.ln.ictenterprises.model.Step;
import com.chinamobile.ln.ictenterprises.model.request.GetContact;
import com.chinamobile.ln.ictenterprises.model.response.ResponseGetContact;
import com.chinamobile.ln.ictenterprises.model.response.ResponseGetContact.Group;
import com.chinamobile.ln.ictenterprises.model.response.ResponseGetContact.LinkMan;
import com.chinamobile.ln.ictenterprises.ui.activity.LoginActivity;
import com.chinamobile.ln.ictenterprises.ui.adapter.EntTreeAdapter;
import com.chinamobile.ln.ictenterprises.utils.JsonUtil;
import com.chinamobile.ln.ictenterprises.utils.Utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

@SuppressLint("HandlerLeak")
public class EntAddressBookFragment extends Fragment
{
    private Context context;
    private EntTreeAdapter adapter;
    private Node ent_root;
    private ListView listView;
    public List<String> selectedNameList = new ArrayList<String>();
    public List<String> selectedAilasList = new ArrayList<String>();
    private List<LinkMan> linkManList = new ArrayList<LinkMan>();
    private List<Group> groupList = new ArrayList<Group>();
    private Controller mHttpManager = null;
    private Node pNode;
    private int position = 1;
    private ProgressDialog dialog;
    private SharedPreferences sharedPref;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        context = getActivity();
        mHttpManager = Controller.getInstance();
        sharedPref = context.getSharedPreferences(Constants.LOGIN_SHAREDPREF,
            Context.MODE_PRIVATE);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState)
    {
        View view = inflater.inflate(R.layout.fragment_ent_addressbook, null);
        listView = (ListView) view.findViewById(R.id.listView);
        listView.setOnItemClickListener(new EntItemClickListener());
        initEntTree();
        return view;
    }

    @Override
    public void onAttach(Activity activity)
    {
        super.onAttach(activity);
    }

    /**
     * 初始化企业地址本
     */
    private void initEntTree()
    {
        // 企业地址本 id为ent_root
        ent_root = new Node("ent_root", Constants.ENT_ADDRESS_BOOK, "", true,
            Constants.IS_FIXED_YES);
        getNodeByPid(ent_root);
    }

    /**
     * 查找地址本
     * @param pNode
     * @return
     */
    private void getNodeByPid(Node pNode)
    {
        GetContact getContact = new GetContact(
            GlobalSetting.GET_NEX_LEVEL_BY_ID, Constants.ENT_ADDRESS_BOOK_TYPE,
            pNode.getId());
        String params = JsonUtil.objectToJson(getContact);
        Step step = Utils.paramsUtil(Config.ADDRESS_BOOK, params);
        dialog = ProgressDialog.show(getActivity(), "", "正在加载数据,请稍等...");
        HttpAsyncTask httpAsyncTask = new HttpAsyncTask(step,
            HttpAsyncTask.CACHE_TYPE_ACTION, sharedPref.getString(
                Constants.COOKIES, ""), GlobalSetting.GET_CONTACT);
        httpAsyncTask.setUIHandler(getEntAddressHandler);
        mHttpManager.execute(httpAsyncTask);
    }

    private Handler getEntAddressHandler = new Handler() {

        public void handleMessage(Message msg)
        {
            if (msg.obj != null)
            {
                @SuppressWarnings("unchecked")
                Map<String, Object> httpMap = (Map<String, Object>) msg.obj;
                int reultCode = (Integer) httpMap
                    .get(GlobalSetting.STUATUS_CODE);
                if (reultCode == GlobalSetting.STUATUS_CODE_SUCCESS)
                {
                    ResponseGetContact responseGetContact = (ResponseGetContact) httpMap
                        .get(GlobalSetting.JSON_GET_CONTACT);
                    if (responseGetContact != null)
                    {
                        if (responseGetContact.resultFlag
                            .equals(GlobalSetting.RESULT_FLAG_SUC))
                        {
                            groupList = responseGetContact.results.group;
                            linkManList = responseGetContact.results.linkMan;
                            if (groupList.size() > 0 || linkManList.size() > 0)
                            {
                                setView();
                            }
                            else
                            {
                                Toast.makeText(context, R.string.no_data,
                                    Toast.LENGTH_SHORT).show();
                            }
                        }
                        else if (responseGetContact.resultFlag
                            .equals(GlobalSetting.RESULT_FLAG_FAIL))
                        {
                            Toast.makeText(context,
                                R.string.get_ent_address_fail,
                                Toast.LENGTH_SHORT).show();
                        }
                    }
                    // httpSend 读取json数据异常 返回null
                    else
                    {
                        Toast.makeText(context, R.string.get_ent_address_fail,
                            Toast.LENGTH_SHORT).show();
                    }
                }
                else if (reultCode == GlobalSetting.STUATUS_CODE_INVALIDATION)
                {
                    Toast.makeText(context, R.string.session_timeout,
                        Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent();
                    intent.setClass(context, LoginActivity.class);
                    startActivity(intent);
                    getActivity().finish();
                }
                else if (reultCode == GlobalSetting.STUATUS_CODE_TIMEROUT)
                {
                    Toast.makeText(context, R.string.network_error,
                        Toast.LENGTH_SHORT).show();
                }
            }
            else
            {
                Toast.makeText(context, R.string.get_ent_address_fail,
                    Toast.LENGTH_SHORT).show();
            }
            dialog.dismiss();
        }
    };

    /**
     * 构造联系人树
     */
    private void nodeTree()
    {
        if (groupList.size() > 0)
        {
            for (Group group : groupList)
            {
                if (pNode == null)
                {
                    Node node = new Node(group.id, group.name, group.alias,
                        true, group.isFixed);
                    node.setParent(ent_root);
                    ent_root.add(node);
                }
                else
                {
                    Node node = new Node(group.id, group.name, group.alias,
                        true, group.isFixed);
                    node.setParent(pNode);
                    pNode.add(node);
                }
            }
            if (pNode != null)
            {
                ent_root.add(pNode);
            }
        }
        if (linkManList.size() > 0)
        {
            for (LinkMan linkMan : linkManList)
            {
                if (pNode == null)
                {
                    Node node = new Node(linkMan.id, linkMan.name,
                        linkMan.alias, false, "");
                    node.setParent(ent_root);
                    ent_root.add(node);
                }
                else
                {
                    Node node = new Node(linkMan.id, linkMan.name,
                        linkMan.alias, false, "");
                    node.setParent(pNode);
                    pNode.add(node);
                }
            }
            if (pNode != null)
            {
                ent_root.add(pNode);
            }
        }
    }

    public void setView()
    {
        nodeTree();
        adapter = new EntTreeAdapter(getActivity(), ent_root);
        if (pNode != null)
        {
            adapter.setExpand(pNode);
        }
        adapter.setCheckBox(true);
        listView.setAdapter(adapter);
        listView.setSelection(position);
    }

    /**
     * 企业地址本树监听
     * @author Administrator
     * 
     */
    public class EntItemClickListener implements OnItemClickListener
    {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int p,
            long arg3)
        {
            position = p;
            Node node = (Node) listView.getAdapter().getItem(position);
            if (node.isLeaf() && node.isGroup())
            {
                pNode = node;
                getNodeByPid(pNode);
            }
            ((EntTreeAdapter) listView.getAdapter()).ExpandOrCollapse(position);
        }
    }
}
